package com.atguigu.examsystemserver.service.impl;


import com.atguigu.examsystemserver.entity.Category;
import com.atguigu.examsystemserver.entity.Question;
import com.atguigu.examsystemserver.exception.ExamException;
import com.atguigu.examsystemserver.mapper.CategoryMapper;
import com.atguigu.examsystemserver.mapper.QuestionMapper;
import com.atguigu.examsystemserver.service.CategoryService;
import com.atguigu.examsystemserver.service.QuestionService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.cj.log.Log;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;


@Slf4j
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper,Category> implements CategoryService {

    @Autowired
    private QuestionMapper questionMapper;

    @Override
    public List<Category> getSelectList() {
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        categoryLambdaQueryWrapper.orderByAsc(Category::getSort);
        List<Category> categoryList = baseMapper.selectList(categoryLambdaQueryWrapper);
        addCategoryQuestionCount(categoryList);
        return categoryList;
    }

    private void addCategoryQuestionCount(List<Category> categoryList) {
        List<Map<String, Long>> categoryQuestionCount = questionMapper.getCategoryQuestionCount();
        Map<Long, Long> collect = categoryQuestionCount.stream().collect(Collectors.toMap(
                key -> key.get("category_id"),
                value -> value.get("count")
        ));
        categoryList.forEach(category -> {
            Long orDefault = collect.getOrDefault(category.getId(), 0L);
            category.setCount(orDefault);
        });
    }

    @Override
    public List<Category> getTreeList() {
        //获取所有的分类，并按照sort排序
        List<Category> categoryList = baseMapper.selectList(new LambdaQueryWrapper<Category>().orderByAsc(Category::getSort));
        addCategoryQuestionCount(categoryList);
        List<Category> builtCategoryTree = buildCategoryTree(categoryList);
        return builtCategoryTree;
    }

    private static List<Category> buildCategoryTree(List<Category> categoryList) {
        Map<Long, List<Category>> collect = categoryList.stream().collect(Collectors.groupingBy(Category::getParentId));
        categoryList.forEach(category -> {
            Long categoryId = category.getId();
            List<Category> childrenCategory = collect.getOrDefault(categoryId, new ArrayList<>());
            category.setChildren(childrenCategory);
            long childerenSumCount = childrenCategory.stream().mapToLong(Category::getCount).sum();
            Long categoryCount = category.getCount();
            category.setCount(categoryCount+childerenSumCount);
        });
        //获取所有parentId为0的分类
        List<Category> categories = categoryList.stream().filter(category -> category.getParentId() == 0).collect(Collectors.toList());
        return categories;
    }

    @Override
    public void saveNewCategory(Category category) {
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        categoryLambdaQueryWrapper.eq(Category::getName,category.getName()).eq(Category::getParentId,category.getParentId());
        boolean exists = baseMapper.exists(categoryLambdaQueryWrapper);
        if (exists){
            Category selectById = baseMapper.selectById(category.getParentId());
            throw new ExamException(444,"在父分类<"+selectById.getName()+">下已经存在 '"+category.getName()+"'");
        }
        baseMapper.insert(category);
    }

    @Override
    public void updateNewCategory(Category category) {
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        categoryLambdaQueryWrapper.eq(Category::getName,category.getName()).eq(Category::getParentId,category.getParentId()).ne(Category::getId,category.getId());
        boolean exists = baseMapper.exists(categoryLambdaQueryWrapper);
        if (exists){
            Category selectById = baseMapper.selectById(category.getParentId());
            throw new ExamException(666,"在父分类<"+selectById.getName()+">下已经存在 '"+category.getName()+"'，请修改一个其他分类名");
        }
        baseMapper.updateById(category);
    }

    @Override
    public void removeCategory(Long id) {
        Long count = baseMapper.selectCount(new LambdaQueryWrapper<Category>().eq(Category::getParentId, id));
        if (count>0){
            throw new ExamException(888,"该分类下有子分类，不能删除");
        }
        Long aLong = questionMapper.selectCount(new LambdaQueryWrapper<Question>().eq(Question::getCategoryId, id));
        if (aLong>0){
            throw new ExamException(999,"该分类下有题目，不能删除");
        }
        removeById(id);
    }

}















